An Introduction to Mathematica

Navigating the Mathematica UI

Mathematica's user interface is organized by a single top title and menu bar, with several child windows beneath. Many other modern editors use this, although Mathematica makes the unusual move of displaying the user's other windows beneath the menu bar. This can sometimes confuse people into thinking they are interacting with the wrong program. Each child window is dedicated to a single Mathematica notebook, a document that can also contain Mathematica commands.



The default size of the characters displayed in a Mathematica notebook is rather small. However, the magnification can easily be 
adjusted by clicking on Window along top toolbar and selecting a more readable magnification, e.g. 150%.



A Mathematica notebook's basic structure is called a "cell." You can see the cell divisions by looking at the right-hand side of the notebook view: each cell is denoted by a single bracket.

You can create a cell by clicking on the border between two cells and typing any letter, symbol, or other input.


Each cell can contain a specific type of content. For example, what you are reading now is located in a text cell. Some examples of  different kinds of cells:

Text cells contain text that has no major stylistic forms, and no executable code.

Item cells contain the elements of a bulleted list

Input cells contain Mathematica code

Section, Subsection, etc cells contain text that is formatted larger and with extra gimmicks so that they are eye-catching.

You can view a cell's designation by right-clicking on a cell's bracket and selecting "Style:"



All cells have certain properties associated with them. These properties may be viewed by selecting a cell, going into the Cell menu, and then going into the Cell Properties submenu:



You can also quickly view a cell's properties by the symbols in the upper part of the bracket. A line parallel to the top of the bracket means that the cell cannot be evaluated - that is, the cell cannot be run as though it contains Mathematica code. A triangle means that the cell can be evaluated. An "x" means that the cell cannot be edited by the user. If the cell can evaluated, but not edited, the "x" will be located below the triangle. Otherwise, the "x" will be located above the line.



These can all be changed by the user at any time through the cell properties submenu, so they are primarily for convenience.

Cells can contain other cells. You can see this with multiple layers of brackets. You can collapse a cell down to just one of its subcells by double-clicking on the subcell that you want to be visible.


It is important to distinguish here between the Mathematica program that you are looking at right now, and the Mathematica program that is executing your Mathematica code. What you are looking at right now is just a fancy interface; when you are using Mathematica to do mathematics, you are not dealing with this interface, but rather you are dealing with another program called the Mathematica Kernel. You are merely using this interface as an intermediary. You can see this by looking at the In and Out designations when you enter commands into Input cells. Each Input cell that has been evaluated contains an In designation, which consists of the word "In" followed by a number in brackets. Each response to an input from the Mathematica kernel has an Out designation, which is the word "Out" followed by the same number in brackets as the input that generated it. These In and Out lines are what the Mathematica kernel is seeing.



What you see when you are dealing with Mathematica is a document editor, but what you are actually using is not a document editor at all; it is more like a chat client.

Arithmetic

We will call any typed string of symbols to be executed by Mathematica' s computational engine (or kernel) an instruction. Instructions are placed inside of input cells. To execute a typed instruction, hit the Ente] key while simultaneously holding down the Shift key. Instructions entered in Mathematica typically appear in black bold type and in Courier font. You can enter instructions for the Mathematica kernel to execute using the same type of notation that is commonly seen in calculators. Here are some examples:

2+5

2-5

2*5

2/5

2^5

Sqrt[9]

5!

Abs[2-5]

Sin[2]

Csc[2]

Entering two numbers separated by a space is assumed to be multiplication:

2 5

In addition, you can use special shortcuts on your keyboard to obtain similar effects. Pressing one of these key combinations does not lead to an ordinary character being entered, but instead typically causes some action to occur or some structure to be created.

({{Ctrl+^ or Ctrl+6,           go to the superscript for a power   }, {Ctrl+/          ,           go to the denominator for a fraction}, {Ctrl+@ or Ctrl+2,           go into a square root               }})

Please try to see if you can input these mathematical expressions :

(2/5)

(5^2)

(Sqrt[9])

Using Assistants

Sometimes, you will see a bit of Mathematica code, but you won't understand the purpose of it. It is in this situation where you will have to use Mathematica's built in help feature. If you highlight a command that you do not know the purpose of and then press F1, you will be taken to a window that shows what that command does. You can try this now with the Erf function:

Erf[2]

You should have gotten something that looks like this:



You can get a more detailed explanation by clicking on the "More Information" button, and there are always several examples.

At other times, you will want Mathematica to do something, but you will not know how to tell Mathematica to do what it is you want it to do. At these times, you have several options available to you. If you press F1 without highlighting anything, you will be brought to the basic help screen. From there, you can perform a search for the command you wish to enter, and the help will give you anything that is related.



Many basic commands are also available in Palettes. If you go to the Palettes menu and select a Palette, a window that contains several buttons will be displayed. Pressing one of these buttons will enter the related Mathematica command in your active document. This allows you to have an interface that is more like a calculator and less like a programming language.



Finally, if you have some idea of the command you wish to enter, but don't remember the name of the command, you can enter the first few letters and then press Ctrl+k. This will bring up the Command Completion interface, which will display every command that begins with the letters that you had typed.

Basic Syntax

Comments

When you write programs in Mathematica, there are various ways to document your code. As always, by far the best thing is to write clear code, and to name the objects you define as explicitly as possible. 
Sometimes, however, you may want to add some "commentary text" to your code, to make it easier to understand. You can add such text at any point in your code simply by enclosing it in matching (* and *). Notice that in Mathematica, "comments" enclosed in (* and *) can be nested in any way.

You can use comments anywhere in the Mathematica code you write.

If[a>b,(*then*) p,(*else*) q]

You can also use text cells to add further explanations. To change the style of the current cell, select the cell style option in the Format menu.  Mathematica instuctions cannot be entered while in text mode.

Variables and Variable Space

Using Mathematica to do arithmetic is fine, but in order to do anything that even remotely pushes Mathematica to its limits will require the use of variables. A variable is a special construct that Mathematica associates with a number or an expression involving other variables. You give these variables meaning by assigning a value to them. Thereafter, Mathematica will keep a record of that variable and its value until you make changes.

There are four basic types of numeric variables: Integers, Rational Numbers, Real Numbers and Complex Numbers. However, unlike some programming languages, you usually don't need to worry about these different variable types. In particular, you don't have to declare a variable before you use it.
In Mathematica, we use "=" to assign a value to a variable. A variable can represent a numerical value, a vector, an expression or even a graph. For example:

x=3

x^2+2x

We can declare different values to different variables simultaneously.

{u,v,w}={1,2,3}

2u+3v+w

Sometimes you may want to clear the value of a previously assigned variable You can use "=." to do this.

{u,v}={1,2} ;   (* assign values to both u and v *)
u=.                (* clear the value of u *)

2u+v

If you want to also clear the variables, you can use the function "Clear".

Clear[u]

Mathematica defines a number of common mathematical constants. These constants can be used both symbolically and with their numerical values (if appropriate). Here are some examples

Pi
N[Pi]

E (* inverse of natural logarithm *)
N[E]

Degree  (* π/180 *)
N[Degree]

Infinity (* Infinity *)
N[Infinity]

GoldenRatio (* Golden Ratio *)
N[GoldenRatio]

The variable "%" refers to the result of the last computation. Similarly, the variable "%%" refers to the result of the second to last computation and so forth. The variable "%n" refers to the result of output "Out[n]".

Obtaining Numerical Answers

If you would like to obtain a decimal represenation for a particular real number, x, then execute the Mathematica instruction N[x]. For example:

N[E]

By default, Mathematica will calculate the decimal number to six significant digits. However, this can be changed by adding
a digits option to the decimal converter operator.

N[E,20]

N[(Sqrt[π]),25]

Multicommands and Suppressing Output

If you wish, you can use several commands at once. The easiest way to do this is to have one command on each line within a cell:

2+3
%-5

You can also have multiple commands on the same line by separating them with a semicolon. If you do this, only the last command will be printed out:

2+3;%-5

Using a semicolon with no extra commands afterward allows you to enter a command but not have it print anything out. You can still access the output using the % command.

2+3;

%

Lists/Tuples

We have previously seen how to make lists of variables using the curly braces {}:

{u,v,w}={1,2,3}

We can make lists of just about anything, even other lists or the outputs of commands:

{u,v,{u,v},N[u+w],w^2,Plot[x,{x,0,1}]}

If we have a list and want only a particular element of the list, we use double square brackets [[]] to pick out an element by its index in the list:

list={u,v,{u,v},N[u+w],w^2,Plot[x,{x,0,1}]}
list[[5]]

Functions

The simplest way to define a function f  in Mathematica is with a mapping instruction of the form f[x]=expr. This assigns the name of  f  to the mapping of the variable  x  into the expression  expr (where, of course,  expr  involves  x  in the case the function  f  is to be nonconstant). Note the underscore after the variable x in the definition. It must be inserted in order for the kernel  to recognize that  x  denotes the independent variable in this definition of the function  f.
     
Consider the following examples :

f[x_]=(x^3)-2 x+1

f[5]

g[x_]=Cos[3x]

g[Pi]

f[g[x]]

Note the difference between a function (like f and g above) and an expression in which a variable depends on other variables. x below is an example of an expression:

x=a+b

It is important to think about how to define your functions. If you use a variable that is already taken, then Mathematica will evaluate your expression first, before doing anything with your function. Consider this function:

x=a+b
f[x_]=x+1
f[2]

We were probably expecting to get the function f(x)=x+1, but instead got the function f(x)=a+b+1. There are two ways to avoid this: either be careful about your variable names and be sure to clear your variables when you are done with them, or use := (a colon followed by an equals sign, often called "gets") instead of =.

:= assigns the delayed value of the right hand side to the left hand side. The right hand side is maintained in an unevaluated form. When the left hand side appears, it is replaced by the right hand side, evaluated afresh each time.  Let's see how := works with the previous example:

x=a+b
f[x_]:=x+1
f[2]

Solving Equations with Mathematica

Mathematica can solve many types of algebraic expressions with ease. The way to do this is with a command called Solve. Solve takes two arguments: the first is a list of equations that you want it to solve, and the second is a list of variables that you want to solve for. It is important to note that to Mathematica, a single equals sign denotes assignment (as with a variable), and two equals signs denotes equality (as with an equation). For example:

Clear[x];
s=Solve[{x^5+12*x^3-4*x==0},{x}]

We used a single equals sign to assign s the value of the output of the Solve command. We used two equals signs to make the equation (x^5)+12 (x^3)-4 x=0. The output of Solve is a list of a special structures called replacement rules. In order to get at the actual answer, we have to specify which answer we want with indexing, and also to enact the replacement with the /. command:

x/.s[[3]]

Solve has many limitations. One of these is that it can't handle an infinite number of solutions. For that, we have to use the Reduce command. It is invoked the same way as Solve, but its output is different:

Solve[{x-Abs[x]==0},{x}]
Reduce[{x-Abs[x]==0},{x}]

Generally, Reduce is more powerful than Solve, but Solve's output (when it produces output) is more immediately useful.

Solve[{x^6+12*x^3-4*x==0},{x}]
Reduce[{x^6+12*x^3-4*x==0},{x}]
N[x/.Solve[{x^6+12*x^3-4*x==0},{x}][[3]],30]

If we don't care about exact solutions and just want a numerical answer to our equations, we can use NSolve. It is used just like Solve and Reduce:

NSolve[{x^6+12*x^3-4*x==0},{x}]

Plotting

In order to plot an expression over an interval, we use an instruction of the form Plot[expr,{var,a,b}]. For example:

Clear[x]
y=3(x^4)-4(x^3)
Plot[y,{x,-2,2}]

Note that the general shape of this graph is not easily recognized due to the large values that y attains when x lies in the interval [-2,1]. We can restrict the range of the plotted curve to to an interval by passing the PlotRange option to plot. Options come after everything else in a command and are entered like this: Option->value.

Plot[y,{x,-2,2},PlotRange->{-1,4}]
Plot[y,{x,-2,2},PlotRange->{{0,1},{-1,4}}]

The PlotStyle option can be insterted in a plot command to control how the plot looks. You can control things like thickness, color, and the style of the line.

Plot[(t^(1/3)),{t,0,5},PlotRange-> {0,1.5},PlotStyle->{Orange,Thickness[0.01],Dashing[Small]}]

You can plot multiple expressions on the same set of axes by giving a list of expressions instead of just one expression:

w=3(x^4)-4(x^3)-12(x^2)+5
v=10(x^3)-43x
Plot[{w,v},{x,-2,2},PlotStyle->{Red,Green,Thick}]

The same thing works for functions:

g[x_]:=(x^2)
h[x_]:=(x^3)
Plot[{g[x],h[x]},{x,-2,2},PlotStyle->{Blue,Magenta,Thick}]

If you are plotting multiple curves at the same time and also want to change the styles, then you must give a list of lists to the PlotStyle option:

Plot[{g[x],h[x],w,v},{x,-2,2},PlotStyle->{{Blue,Thick},{Magenta,Thick},{Dashing[Tiny]},{Dashing[Large]}}]

If you are plotting a curve in which the y coordinate is not a function of the x coordinate, you have to use the ContourPlot command. ContourPlot works just like plot, only instead of giving it an expression to plot, you give it an equation:

ContourPlot[x^4+(-4+y) y^3+2 x^2 (-2-2 y+y^2)==0,{x,-4.7,4.7},{y,-3,5}]

Changing the style requires the use of the ContourStyle option instead of the PlotStyle option:

ContourPlot[x^4+(-4+y) y^3+2 x^2 (-2-2 y+y^2)==0,{x,-4.7,4.7},{y,-3,5}, ContourStyle-> {Magenta,Thickness[.003]}]

In order to make our plots more legible and give them meaning, we can add text to them. We can append a label to the top of the plot using the PlotLabel option:

ContourPlot[x^4+(-4+y) y^3+2 x^2 (-2-2 y+y^2)==0,{x,-4.7,4.7},{y,-3,5}, ContourStyle-> {Magenta,Thickness[.003]},PlotLabel-> "A Cardioid"]

We can add labels to the axes using the AxesLabel option:

Plot[-x^2+20x+1,{x,0,10},AxesLabel-> {"Time (h)", "Pressure (kbar)"}]

We can put text on a set of axes using the Graphics and Text commands:

Graphics[Text["A Cardioid",{1.25,4.5}]]

Putting them on the same set of axes as a plot requires that we use the Show command and give it all of the commands at once:

Show[ContourPlot[x^4+(-4+y) y^3+2 x^2 (-2-2 y+y^2)==0,{x,-4.7,4.7},{y,-3,5}, ContourStyle-> {Magenta,Thickness[.003]}],Graphics[Text["The cardioid: (x^4)+(y-4)(y^3)+2(x^2)((y^2)-2y-2)=0",{1.25,4.5}]]]

We can simplify this process by assigning the plots and text to variables:

M=ContourPlot[x^4+(-4+y) y^3+2 x^2 (-2-2 y+y^2)==0,{x,-4.7,4.7},{y,-3,5}, ContourStyle-> {Magenta,Thickness[.003]}]
T=Graphics[Text["The cardioid: (x^4)+(y-4)(y^3)+2(x^2)((y^2)-2y-2)=0",{1.25,4.5}]]
Show[M,T]

Doing Calculus with Mathematica

Mathematica can also understand Calculus. Mathematica can evaluate limits using the Limit command. Be aware that Mathematica does not check for some types of nonexistent limits:

Limit[Sin[x]/x,x-> 0]
Limit[UnitStep[x],x-> 0]
Plot[UnitStep[x],{x,-0.1,0.1}]

If we pass the additional Direction option, we can specify the direction. A direction of 1 means it comes from the right, and a direction of -1 means it comes from the left:

Limit[UnitStep[x],x-> 0, Direction-> -1]
Limit[UnitStep[x],x-> 0,Direction-> 1]

We can differentiate with the command D. We must give D both the expression to differentiate and the variable by which to differentiate. An easy way to remember this is that it works just like Leibniz notation.

D[t^4-t^3+t^2,t]

To obtain an antiderivative, we use the Integrate command. Mathematica does not give all antiderivatives with this command. It works just like D on the surface:

Integrate[x^4-x^3+x^2,x]

If we change Integrate's second argument into a list containing the variable and minimum and maximum values (like with Plot), we get a definite integral:

Integrate[x^4-x^3+x^2,{x,0,2}]

Exercises

Assignment 1: Solving a System of Equations

Given the system of equations:

y=2x+2
y=2(x^3)+7(x^2)-x-2

Find the three solutions via the following four methods, and compare your results:

Graphically, by plotting the two expressions and estimating the points of intersection.

Through the use of the Solve command.

Through the use of the Reduce command.

Through the use of the NSolve command.

Useful commands for this exercise:

Plot[{function1name[variable],function2name[variable]},{variable,leftborder,rightborder},PlotRange->{lowborder,highborder}, PlotLabel->Title] plots two functions and explicitly gives the range of coordinates over which to plot. It also allows you to specify a title.

Solve[{expression1==expression2, expression3==expression4},{variable1,variable2}] solves symbolically for the situation where expression1 is equal to expression2 and expression3 is equal to expression4.

Reduce[{expression1==expression2, expression3==expression4},{variable1,variable2}] solves symbolically for the situation where expression1 is equal to expression2 and expression3 is equal to expression4.

NSolve[{expression1==expression2, expression3==expression4},{variable1,variable2}] solves numerically for the situation where expression1 is equal to expression2 and expression3 is equal to expression4.

Assignment 2: Fun with Plots

Plot the following trigonometric functions:

Inverse Sine

Inverse Tangent

Inverse Cotangent

Subject to the following restrictions:

The plot regions should be the corresponding functions' natural domain. If the natural domain is [-∞,∞], then the region should be [-5,5].

The curves represented by the functions should be indicated with a solid blue line.

All asymptotes, if any, should be also plotted on the same set of axes. They should be represented by a dotted red line.

The plots should be clearly labeled with the name of the function being plotted.

Useful commands for this exercise:

Plot[functionname[variable],{variable,leftborder,rightborder},PlotRange->{lowborder,highborder}, PlotLabel->Title] plots a function and explicitly gives the range of coordinates over which to plot. It also allows you to specify a title.

Plot[{function1name[variable],function2name[variable],function3name[variable]}, {variable,leftborder,rightborder}, PlotStyle->{{Color1,Dotted1},{Color2,Dotted2},{Color3,Dotted3}}, PlotRange->{lowborder,highborder}, PlotLabel->Title,] plots three functions and explicitly gives the range of coordinates over which to plot. It also specifies color and dotted information and includes a title.

Assignment 3: The Curious Expression, (((1+(1/x)))^x)

As x-> ∞, the inner component of (((1+(1/x)))^x) goes to 1, and the exponent gets huge. For short, people often write this as (1^∞), this is an "indeterminate form," which is to say that the answer is not obvious. Is the limit 1? Does the limit go to infinity? How does the limit change if we change the inner expression to something like (1+((ln 2)/x))? Investigate this expression. Your answer should include:

A plot of (1+(1/x)) that includes a large enough value for x to show that the limit is most likely not 1.

An evaluation of the limit of (((1+(1/x)))^x) as x-> ∞.

An evaluation of the limit of (((1+((ln 2)/x)))^x)as x-> ∞.

A conjecture as to the value of the limit of (((1+(c/x)))^x) as x-> ∞.

Useful commands for this exercise:

Plot[expression,{variable,leftborder,rightborder}] plots an expression in one variable over a region.

Limit[functionname[variable],variable->limit] evaluates a limit.